<template>
  <div id="sensitiveResultRuleDiv">
    <!-- <Breadcrumb content="药敏结果敏感性规则" /> -->
    <Splitpanes>
      <Pane size="50">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" @click="findSensitiveResultRuleList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="addSensitiveResultRule"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveSensitiveResultRuleList"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="batchDeleteSensitiveResultRule"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <vxe-table ref="mdrRuleTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="sensitiveResultRuleList" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" @current-change='sampleRowClick' resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="30"></vxe-column>
            <vxe-column field="roleCode" title="规则编码" width="100" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.roleCode }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.roleCode" placeholder="请输入规则编码" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="roleName" title="规则名称" width="100" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.roleName }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.roleName" placeholder="请输入规则编码" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="antNo" title="抗生素编码" width="100" align="center">
              <template #default="{ row }">
                <div>{{ row.antNo }}</div>
              </template>
            </vxe-column>
            <vxe-column field="antNa" title="抗生素" width="200" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <VxePulldownSelection :isChild="true" :childIndex="rowIndex" :url="'/lis/bacAntibioticsDict/findAntDictList'" @confirmClick="pulldownSelectAnt" :tableColumn="[
              { field: 'antCode', title: '编码' },
              { field: 'antName', title: '名称', }
              ]" :aimKeys="[
               { aimKey: 'antNa', rowKey: 'antName' },
               { aimKey: 'antNo', rowKey: 'antCode' }
              ]" :displayTexts="['antNa']" :displayTextObj="row.antNa ? row.antNa : ''" />
              </template>
            </vxe-column>
            <vxe-column field="sensitiveNo" title="敏感性编码" width="80" align="center">
              <template #default="{ row }">
                <div>{{ row.sensitiveNo }}</div>
              </template>
            </vxe-column>
            <vxe-column field="sensitiveNa" title="敏感性" width="150" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <VxePulldownSelection :isChild="true" :childIndex="rowIndex" :url="'/lis/bac/base/interpretation-code/dict/findBacInterpretationCodeDictList'" @confirmClick="pulldownSelectConfirm" :tableColumn="[
              { field: 'code', title: '编码' },
              { field: 'name', title: '名称', }
              ]" :aimKeys="[
               { aimKey: 'sensitiveNa', rowKey: 'name' },
               { aimKey: 'sensitiveNo', rowKey: 'code' }
              ]" :displayTexts="['sensitiveNa']" :displayTextObj="row.sensitiveNa ? row.sensitiveNa : ''" />
              </template>
            </vxe-column>
            <vxe-column field="seq" title="顺序" width="150" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.seq" placeholder="" type="text" clearable></vxe-input>
              </template>
            </vxe-column>

          </vxe-table>
        </div>
      </Pane>
      <pane size="50">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="addRule"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="savetRuleList"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <vxe-table class="mytable-scrollbar" align="left" border="inner" ref="roleDetailsRef" height="auto" :row-config="{ isCurrent: true, isHover: true }" :tree-config="{}" :column-config="{ resizable: true }" :data="ruleList" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
            <vxe-column field="antNo" title="抗生素编码" width="100" align="center">
              <template #default="{ row }">
                <div>{{ row.antNo }}</div>
              </template>
            </vxe-column>
            <vxe-column field="antNa" title="抗生素" width="200" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <VxePulldownSelection :isChild="true" :childIndex="rowIndex" :url="'/lis/bacAntibioticsDict/findAntDictList'" @confirmClick="pulldownSelectAntDetails" :tableColumn="[
              { field: 'antCode', title: '编码' },
              { field: 'antName', title: '名称', }
              ]" :aimKeys="[
               { aimKey: 'antNa', rowKey: 'antName' },
               { aimKey: 'antNo', rowKey: 'antCode' }
              ]" :displayTexts="['antNa']" :displayTextObj="row.antNa ? row.antNa : ''" />
              </template>
            </vxe-column>
            <vxe-column title="条件" tree-node align="center" width="150">
              <template #default="{ row }">
                {{'='}}
              </template>
            </vxe-column>
            <vxe-column field="sensitiveNo" title="敏感性编码" width="150" align="center">
              <template #default="{ row }">
                <div>{{ row.sensitiveNo }}</div>
              </template>
            </vxe-column>
            <vxe-column field="sensitiveNa" title="敏感性" width="150" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <VxePulldownSelection :isChild="true" :childIndex="rowIndex" :url="'/lis/bac/base/interpretation-code/dict/findBacInterpretationCodeDictList'" @confirmClick="pulldownSelectConfirmDetails" :tableColumn="[
              { field: 'code', title: '编码' },
              { field: 'name', title: '名称', }
              ]" :aimKeys="[
               { aimKey: 'sensitiveNa', rowKey: 'name' },
               { aimKey: 'sensitiveNo', rowKey: 'code' }
              ]" :displayTexts="['sensitiveNa']" :displayTextObj="row.sensitiveNa ? row.sensitiveNa : ''" />
              </template>
            </vxe-column>
            <!--            <vxe-column field="leftBracket" title="左括号" tree-node :edit-render="{ autofocus: '.vxe-input&#45;&#45;inner' }" align="left">
              <template #edit="{ row }">
                <vxe-input v-model="row.leftBracket" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="symbol" title="条件" tree-node :edit-render="{ autofocus: '.vxe-input&#45;&#45;inner' }" align="left">
              <template #edit="{ row }">
                <vxe-select v-model="row.symbol" placeholder="请选择关联方式" clearable transfer>
                  <vxe-option v-for="resultSign in symbolList" :key="resultSign.value" :label="resultSign.value" :value="resultSign.value"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="rightBracket" title="右括号" tree-node :edit-render="{ autofocus: '.vxe-input&#45;&#45;inner' }" align="left">
              <template #edit="{ row }">
                <vxe-input v-model="row.rightBracket" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="relation" title="关联" tree-node :edit-render="{ autofocus: '.vxe-input&#45;&#45;inner' }" align="left">
              <template #edit="{ row }">
                <vxe-select v-model="row.relation" placeholder="请选择关联方式" clearable transfer>
                  <vxe-option v-for="resultSign in relationList" :key="resultSign.value" :label="resultSign.value" :value="resultSign.value"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>-->
            <vxe-column title="操作" fixed="right">
              <template #default="{ row }">
                <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteRoleDetails(row)" class="spanIcon"></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </pane>
    </Splitpanes>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
defineExpose({ initPage });

let sensitiveResultRuleList: any = reactive([]); //左侧仪器表格数据
let ruleList: any = reactive([]); //右侧规则
let rloading = ref(false);
let sltInstrSample: any = {};

function initPage() {
  findSensitiveResultRuleList();
}
onMounted(() => {
  //findSensitiveResultRuleList();
});

// 获取左侧仪器表格数据+刷新+右侧表格数据
function findSensitiveResultRuleList() {
  rloading.value = true;
  sensitiveResultRuleList.length = 0; //放入数据前清空数据
  const url = '/bac/drugResultSenrole/findSenroleList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {}
    })
    .then((res: any) => {
      sensitiveResultRuleList.push(...res.data);
      if (sensitiveResultRuleList.length > 0) {
        sampleRowClick({ row: sensitiveResultRuleList[0] });
      } else {
        ruleList.length = 0; //放入数据前清空数据
        sltInstrSample = {};
      }
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

// 获取右侧的明细数据
function findSenRoleDetailsRuleList() {
  rloading.value = true;
  ruleList.length = 0; //放入数据前清空数据
  const url = '/bac/drugResultSenrole/findSenroleDetailsList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { roleCode: sltInstrSample.roleCode }
    })
    .then((res: any) => {
      ruleList.push(...res.data);
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

// 左侧新增
function addSensitiveResultRule() {
  const record: any = {
    id: '',
    roleCode: '',
    roleName: '',
    antNo: '',
    antNa: '',
    sensitiveNo: '',
    sensitiveNa: '',
    seq: sensitiveResultRuleList.length + 1,
    orgId: ''
  };
  sensitiveResultRuleList.push(record);
  ruleList.length = 0;
}
//右侧新增
function addRule() {
  if (isEmpty(sltInstrSample.roleCode)) {
    VxeMessage('请选择规则', VxeNotifyType.error);
  }
  const record: any = {
    id: '',
    roleCode: sltInstrSample.roleCode,
    antNo: '',
    antNa: '',
    sensitiveNo: '',
    sensitiveNa: '',
    seq: ruleList.length + 1,
    orgId: ''
  };
  ruleList.push(record);
}

// 左侧保存
async function saveSensitiveResultRuleList() {
  let $Xtable = proxy.$refs.mdrRuleTableRef;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id && p.id !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = sensitiveResultRuleList.filter((e: any) => {
      return !e.id || e.id === '';
    });

    const sveOrupdateRules = [] as any[];
    updateRecords.forEach((e: any) => {
      const iIRule: any = {
        id: e.id,
        roleCode: e.roleCode,
        roleName: e.roleName,
        antNo: e.antNo,
        antNa: e.antNa,
        sensitiveNo: e.sensitiveNo,
        sensitiveNa: e.sensitiveNa,
        seq: e.seq,
        orgId: e.orgId
      };
      if (isEmpty(iIRule.sensitiveNo)) {
        iIRule.sensitiveNo = '';
      }
      sveOrupdateRules.push(iIRule);
    });
    InsertRecords.forEach((e: any) => {
      const iIRule: any = {
        roleCode: e.roleCode,
        roleName: e.roleName,
        antNo: e.antNo,
        antNa: e.antNa,
        sensitiveNo: e.sensitiveNo,
        sensitiveNa: e.sensitiveNa,
        seq: e.seq,
        orgId: e.orgId
      };
      if (isEmpty(iIRule.sensitiveNo)) {
        iIRule.sensitiveNo = '';
      }
      sveOrupdateRules.push(iIRule);
    });

    if (sveOrupdateRules.length > 0) {
      const url = '/bac/drugResultSenrole/saveOrUpdateSenrole';
      proxy.$http
        .post(url, sveOrupdateRules)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);
          setTimeout(() => {
            findSensitiveResultRuleList();
          }, 500);
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
}
//右侧保存
async function savetRuleList() {
  let $Xtable = proxy.$refs.roleDetailsRef;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id && p.id !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = ruleList.filter((e: any) => {
      return !e.id || e.id === '';
    });

    const sveOrupdateRules = [] as any[];
    updateRecords.forEach((e: any) => {
      const iIRule: any = {
        id: e.id,
        roleCode: e.roleCode,
        antNo: e.antNo,
        antNa: e.antNa,
        sensitiveNo: e.sensitiveNo,
        sensitiveNa: e.sensitiveNa,
        seq: e.seq,
        orgId: e.orgId
      };
      if (isEmpty(iIRule.sensitiveNo)) {
        iIRule.sensitiveNo = '';
      }
      sveOrupdateRules.push(iIRule);
    });
    InsertRecords.forEach((e: any) => {
      const iIRule: any = {
        roleCode: e.roleCode,
        antNo: e.antNo,
        antNa: e.antNa,
        sensitiveNo: e.sensitiveNo,
        sensitiveNa: e.sensitiveNa,
        seq: e.seq,
        orgId: e.orgId
      };
      if (isEmpty(iIRule.sensitiveNo)) {
        iIRule.sensitiveNo = '';
      }
      sveOrupdateRules.push(iIRule);
    });

    if (sveOrupdateRules.length > 0) {
      const url = '/bac/drugResultSenrole/saveOrUpdateSenroleDeatils';
      proxy.$http
        .post(url, sveOrupdateRules)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);
          setTimeout(() => {
            findSenRoleDetailsRuleList();
          }, 500);
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
}
function deleteRoleDetails(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const index = ruleList.findIndex((item) => item == row);
      ruleList.splice(index, 1);
      if (!isEmpty(row.id)) {
        const url = '/bac/drugResultSenrole/deleteSenroleRuleDetails';
        proxy.$http
          .post(url, row)
          .then((res: any) => {
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      }
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// 左侧删除
function batchDeleteSensitiveResultRule() {
  const sltInstrSamples = (proxy.$refs.mdrRuleTableRef as any).getCheckboxRecords();
  if (!(sltInstrSamples.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delInstrSampleList = sltInstrSamples.filter((p: any) => !isEmpty(p.id));
        if (delInstrSampleList.length > 0) {
          const url = '/bac/drugResultSenrole/batchDeleteSenroleRule';
          proxy.$http
            .post(url, delInstrSampleList)
            .then((res: any) => {
              findSensitiveResultRuleList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeInstrSampleList = sltInstrSamples.filter((p: any) => isEmpty(p.id));
        if (removeInstrSampleList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.mdrRuleTableRef;
          if ($Xtable) {
            for (const removeRow of removeInstrSampleList) {
              const iindex = sensitiveResultRuleList.findIndex((item) => item == removeRow);
              sensitiveResultRuleList.splice(iindex, 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 左侧表格 点击当前行
function sampleRowClick({ row }) {
  if (isEmpty(row)) {
    sltInstrSample = {};
    ruleList.length = 0; //放入数据前清空数据
  } else {
    (proxy.$refs.mdrRuleTableRef as any).setCurrentRow(row);
    sltInstrSample = row;
    findSenRoleDetailsRuleList();
  }
}

function pulldownSelectAnt(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      sensitiveResultRuleList[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
function pulldownSelectConfirm(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      sensitiveResultRuleList[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
function pulldownSelectAntDetails(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      ruleList[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
function pulldownSelectConfirmDetails(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      ruleList[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
</script>

<style lang="scss" scoped>
#sensitiveResultRuleDiv {
  height: 100%;
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .roleTable {
    height: calc(100% - 40px);
    background-color: $base-white;
  }

  .tableBox {
    height: calc(100% - 40px);
  }
}
</style>
